<template>
  <el-upload
    :class="className"
    :show-file-list="false"
    :on-success="handleSuccess"
    :before-upload="beforeUpload"
    :action="uploadApi"
    :headers="{ token }"
    name="image"
    drag
    accept="image/jpeg, image/png"
  >
    <img v-if="value" :src="value" class="img" />
    <template v-else>
      <i v-if="skin === 'small'" class="el-icon-plus uploader-icon"></i>
      <template v-else>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将图片拖到此处，或
          <em>点击上传</em>
        </div>
      </template>
    </template>
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件，且不超过3MB
      <span v-if="tipSize">，图片尺寸：{{ tipSize }}</span>
    </div>
  </el-upload>
</template>
<script>
import { uploadApi } from '@/api/common'
import { getToken } from '@/utils/auth'
console.log('uploadApi', uploadApi)
export default {
  name: 'ImgUpload',
  props: {
    className: {
      type: String,
      default: ''
    },
    tipSize: {
      type: String,
      default: ''
    },
    value: {
      type: String,
      default: ''
    },
    skin: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      uploadApi,
      token: getToken()
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt3M = file.size / 1024 / 1024 < 3
      if (!isLt3M) {
        this.$message.error('上传图片大小不能超过 3MB!')
      }
      return isLt3M
    },
    handleSuccess(res) {
      if (res.code === 20000) {
        this.$emit('input', res.data.url)
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        })
      }
    }
  }
}
</script>
<style scoped>
.img {
  max-width: 100%;
  max-height: 100%;
}
.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 65px;
  height: 65px;
  line-height: 65px;
  text-align: center;
}
</style>
